import React, { useEffect, useState, useRef } from 'react'
import { NavBar, Toast, SpinLoading, Button, Avatar, List } from 'antd-mobile'
import { useNavigate, useParams } from 'react-router-dom'
import { getDoctorInfo, followDoctor, cancelFollowDoctor, type DoctorInfo, type DoctorGift, type DoctorComment } from '../../api/doctor'
import { useSelector } from 'react-redux'
import type { RootState } from '../../store/types'
import { hasPermission } from '../../utils/permission'
import './index.css'

function DoctorDetail() {
  const navigate = useNavigate()
  const { doctorId } = useParams<{ doctorId: string }>()
  const userEmail = useSelector((state: RootState) => state.info.email)
  const [doctorInfo, setDoctorInfo] = useState<DoctorInfo | null>(null)
  const [loading, setLoading] = useState(true)
  const [isSticky, setIsSticky] = useState(false)
  const stickyRef = useRef<HTMLDivElement>(null)
  const [isFollowed, setIsFollowed] = useState(false)

  // 返回上一页
  const handleBack = () => {
    navigate(-1)
  }

  // 获取医生详情信息
  const fetchDoctorInfo = async () => {
    if (!doctorId) {
      Toast.show({ content: '医生ID不存在' })
      return
    }

    try {
      setLoading(true)
      const response = await getDoctorInfo(parseInt(doctorId))
      if (response.status === '0000') {
        // 获取本地存储的关注状态
        const followedDoctors = JSON.parse(localStorage.getItem('followedDoctors') || '[]')
        const doctorData = response.result
        
        // 如果API没有返回关注状态，从本地存储恢复
        if (doctorData.followFlag === undefined || doctorData.followFlag === null) {
          doctorData.followFlag = followedDoctors.includes(doctorData.doctorId) ? 1 : 0
        }
        
        // 设置关注状态
        const shouldFollow = doctorData.followFlag === 1
        setIsFollowed(shouldFollow)
        setDoctorInfo(doctorData)
      } else {
        Toast.show({ content: response.message || '获取医生信息失败' })
      }
    } catch (error) {
      console.error('获取医生信息失败:', error)
      Toast.show({ content: '网络错误，请重试' })
    } finally {
      setLoading(false)
    }
  }

  // 格式化时间
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  // 关注/取消关注医生
  const handleFollow = async () => {
    if (!doctorInfo) return
    
    try {
      if (isFollowed) {
        // 取消关注
        const response = await cancelFollowDoctor(doctorInfo.doctorId)
        if (response.status === '0000') {
          Toast.show({ content: response.message || '取消关注成功' })
          setIsFollowed(false)
          // 更新本地存储
          const followedDoctors = JSON.parse(localStorage.getItem('followedDoctors') || '[]')
          const updatedFollowedDoctors = followedDoctors.filter((id: number) => id !== doctorInfo.doctorId)
          localStorage.setItem('followedDoctors', JSON.stringify(updatedFollowedDoctors))
        } else {
          Toast.show({ content: response.message || '取消关注失败' })
        }
      } else {
        // 关注
        const response = await followDoctor(doctorInfo.doctorId)
        if (response.status === '0000') {
          Toast.show({ content: response.message || '关注成功' })
          setIsFollowed(true)
          // 更新本地存储
          const followedDoctors = JSON.parse(localStorage.getItem('followedDoctors') || '[]')
          if (!followedDoctors.includes(doctorInfo.doctorId)) {
            followedDoctors.push(doctorInfo.doctorId)
            localStorage.setItem('followedDoctors', JSON.stringify(followedDoctors))
          }
        } else {
          Toast.show({ content: response.message || '关注失败' })
          console.error('handleFollow: 关注API失败，状态码:', response.status, '消息:', response.message)
        }
      }
    } catch (error) {
      console.error('关注操作失败:', error)
      Toast.show({ content: '网络错误，请重试' })
        }
  }

  // 在线问诊
  const handleConsultation = () => {
    // 权限检查已经在PermissionGuard中完成，这里直接执行功能
    Toast.show({ content: '在线问诊功能开发中' })
  }

  // 监听滚动事件，实现吸顶效果
  useEffect(() => {
    const handleScroll = () => {
      if (stickyRef.current) {
        const rect = stickyRef.current.getBoundingClientRect()
        setIsSticky(rect.top <= 0)
      }
    }

    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  useEffect(() => {
    fetchDoctorInfo()
  }, [doctorId])

  if (loading) {
    return (
      <div className="doctor-detail-loading">
        <SpinLoading color="primary" />
        <p>加载中...</p>
      </div>
    )
  }

  if (!doctorInfo) {
    return (
      <div className="doctor-detail-error">
        <p>医生信息不存在</p>
        <Button onClick={handleBack}>返回</Button>
      </div>
    )
  }

  return (
    <div className="doctor-detail-container">
      {/* 头部导航栏 */}
      <NavBar onBack={handleBack} className="doctor-detail-navbar">
        医生详情
      </NavBar>

      {/* 吸顶导航 */}
      <div className={`sticky-nav ${isSticky ? 'sticky' : ''}`}>
        <div className="sticky-nav-content">
          <div className="sticky-doctor-info">
            <Avatar
              src={doctorInfo?.imagePic}
              fallback="http://10.59.9.18/images/health/doctor/default.jpg"
              style={{ '--size': '40px' }}
            />
            <div className="sticky-doctor-details">
              <div className="sticky-doctor-name">{doctorInfo?.doctorName}</div>
              <div className="sticky-doctor-title">{doctorInfo?.jobTitle}</div>
            </div>
          </div>
          <Button 
            color="primary" 
            size="small"
            onClick={() => {
              // 检查权限，如果没有权限则提示
              if (!userEmail) {
                Toast.show('请先登录')
                return
              }
              if (!hasPermission(userEmail, 'consultation')) {
                Toast.show('暂无权限，无法在线咨询')
                return
              }
              handleConsultation()
            }}
          >
            立即咨询
          </Button>
        </div>
      </div>

      {/* 医生基本信息 */}
      <div className="doctor-basic-info" ref={stickyRef}>
        <div className="doctor-header">
          <div className="doctor-avatar">
            <Avatar
              src={doctorInfo.imagePic}
              fallback="http://10.59.9.18/images/health/doctor/default.jpg"
              style={{ '--size': '80px' }}
            />
          </div>
          <div className="doctor-info">
            <h2 className="doctor-name">{doctorInfo.doctorName}</h2>
            <p className="doctor-title">{doctorInfo.jobTitle}</p>
            <p className="doctor-hospital">{doctorInfo.inauguralHospital}</p>
            <div className="doctor-stats">
              <span className="praise-rate">好评率 {doctorInfo.praise}%</span>
              <span className="service-count">服务 {doctorInfo.serverNum} 人</span>
            </div>
          </div>
                                 <div className="doctor-actions">
              <Button 
                size="small" 
                color={isFollowed ? 'default' : 'primary'}
                onClick={() => {
                  // 检查权限，如果没有权限则提示
                  if (!userEmail) {
                    Toast.show('请先登录')
                    return
                  }
                                if (!hasPermission(userEmail, 'follow')) {
                Toast.show('暂无权限，无法关注')
                return
              }
                  handleFollow()
                }}
                style={{
                  backgroundColor: isFollowed ? '#f5f5f5' : undefined,
                  color: isFollowed ? '#999' : undefined,
                  borderColor: isFollowed ? '#d9d9d9' : undefined
                }}
              >
                {isFollowed ? '已关注' : '关注'}
              </Button>
            </div>
        </div>
        
        <div className="doctor-price-section">
          <span className="price-label">咨询价格</span>
          <span className="price-value">¥{doctorInfo.servicePrice}</span>
          <Button 
            color="primary" 
            size="small"
            onClick={() => {
              // 检查权限，如果没有权限则提示
              if (!userEmail) {
                Toast.show('请先登录')
                return
              }
              if (!hasPermission(userEmail, 'consultation')) {
                Toast.show('暂无权限，无法在线咨询')
                return
              }
              handleConsultation()
            }}
            className="consultation-btn"
          >
            立即咨询
          </Button>
        </div>
      </div>

      {/* 个人简介 */}
      {doctorInfo.personalProfile && (
        <div className="info-section">
          <h3 className="section-title">个人简介</h3>
          <div className="section-content">
            <p>{doctorInfo.personalProfile}</p>
          </div>
        </div>
      )}

      {/* 擅长领域 */}
      {doctorInfo.goodField && (
        <div className="info-section">
          <h3 className="section-title">擅长领域</h3>
          <div className="section-content">
            <p>{doctorInfo.goodField}</p>
          </div>
        </div>
      )}

      {/* 评价统计 */}
      <div className="info-section">
        <h3 className="section-title">评价统计</h3>
        <div className="comment-stats">
          <div className="stat-item">
            <span className="stat-number">{doctorInfo.commentNum}</span>
            <span className="stat-label">总评价</span>
          </div>
          <div className="stat-item">
            <span className="stat-number positive">{doctorInfo.praiseNum}</span>
            <span className="stat-label">好评</span>
          </div>
          <div className="stat-item">
            <span className="stat-number negative">{doctorInfo.badNum}</span>
            <span className="stat-label">差评</span>
          </div>
        </div>
      </div>

      {/* 收到的礼物 */}
      {doctorInfo.doctorReceiveGiftList && doctorInfo.doctorReceiveGiftList.length > 0 && (
        <div className="info-section">
          <h3 className="section-title">收到的礼物</h3>
                     <div className="gifts-grid">
             {doctorInfo.doctorReceiveGiftList.map((gift: DoctorGift, index: number) => (
               <div key={index} className="gift-item">
                <div className="gift-image">
                  <img src={gift.giftPic} alt={gift.giftName} />
                </div>
                <div className="gift-info">
                  <div className="gift-name">{gift.giftName}</div>
                  <div className="gift-worth">价值: {gift.worth}</div>
                  <div className="gift-count">收到: {gift.receiveNum}</div>
                  {gift.meaning && <div className="gift-meaning">{gift.meaning}</div>}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 用户评论 */}
      {doctorInfo.commentList && doctorInfo.commentList.length > 0 && (
        <div className="info-section">
          <h3 className="section-title">用户评论</h3>
                     <List className="comment-list">
             {doctorInfo.commentList.map((comment: DoctorComment, index: number) => (
               <List.Item key={index} className="comment-item">
                 <div className="comment-header">
                   <Avatar
                     src="http://10.59.9.18/images/health/doctor/default.jpg"
                     style={{ '--size': '40px' }}
                   />
                   <div className="comment-info">
                     <div className="comment-author">{comment.nickName}</div>
                     <div className="comment-time">{formatTime(comment.commentTime)}</div>
                   </div>
                 </div>
                 <div className="comment-content">
                   {comment.content}
                 </div>
               </List.Item>
            ))}
          </List>
        </div>
      )}
    </div>
  )
}

export default DoctorDetail
